import dayjs from "dayjs";
import { GetAllDelegateTeamByClassId } from "@/api/teacher/delegateTeam";
import { GetAllClass } from "@/api/teacher/zsclass";
import {
  GetPageStu,
  SaveStudent,
  Delete,
  BatchAddStu
} from "@/api/admin/teacher";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
// import Enumerable from "linq";
export function useStudent() {
  const form = reactive({
    ClassId: "",
    DelegateTeamId: ""
  });

  const addStudentDto = reactive({
    ClassId: "",
    DelegateTeamNum: 0,
    PasswordType: "",
    Password: "",
    ExpirationTime: ""
  });

  const updateStudentDto = reactive({
    UserName: "",
    PassWord: "",
    UserId: "",
    Sex: "",
    DelegateTeamId: 0,
    TelePhone: "",
    Email: "",
    Remark: "",
    StudentNumber: "",
    ExpirationTime: "",
    LoginIP: "",
    ClassId: ""
  });

  const sex = ref([
    { id: 1, name: "男" },
    { id: 2, name: "女" }
  ]);
  const classList = ref([]);
  const delegateTeamList = ref([]);
  const dataList = ref([]);
  const loading = ref(false);
  const updatePanelVisible = ref(false);
  const addPanelVisible = ref(false);

  const rules = {
    ClassId: [
      {
        required: true,
        message: "请选择班级！",
        trigger: ["blur", "change"]
      }
    ],
    DelegateTeamNum: [
      {
        required: true,
        message: "请输入代表队数量！",
        trigger: ["blur", "change"]
      }
    ],

    PasswordType: [
      {
        required: true,
        message: "请选择默认密码！",
        trigger: ["blur", "change"]
      }
    ],
    ExpirationTime: [
      {
        required: true,
        message: "请设置到期时间！",
        trigger: ["blur", "change"]
      }
    ],
    TelePhone: [
      {
        validator: (rule: any, value: any, callback: any) => {
          const tealRegex = /^1[3456789]\d{9}$/;
          console.log("123", value)
          if (tealRegex.test(value) || !value.length) {
            callback();
          } else {
            callback(new Error("请输入正确的手机号"));
          }
          // if (value === "" || value == 0) {
          //   callback(new Error("请输入用户数量"));
          // } else if (Number(value) < 0) {
          //   callback(new Error("用户数量不能为负数"));
          //   updateClassDto.UserNum = 0;
          // } else {
          //   callback();
          // }
        },
        trigger: ['blur', 'change'],
      },
    ],
    Email: [
      {
        type: 'email',
        message: '请输入正确的邮箱号',
        trigger: ['blur', 'change'],
      },
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 80
    },
    {
      label: "学生账号",
      prop: "userId",
      minWidth: 100
    },
    {
      label: "密码",
      prop: "passWord",
      minWidth: 100
    },
    {
      label: "学生名称",
      prop: "userName",
      minWidth: 100
    },
    {
      label: "学号",
      prop: "studentNumber",
      minWidth: 100
    },
    {
      label: "团队名称",
      prop: "delegateTeamName",
      minWidth: 100
    },
    {
      label: "性别",
      prop: "sex",
      minWidth: 55,
      cellRenderer: ({ row }) => (
        <el-tag type={row.sex === 2 ? "danger" : ""} effect="plain">
          {row.sex === 1 ? "男" : "女"}
        </el-tag>
      )
    },
    {
      label: "联系电话",
      prop: "telePhone",
      minWidth: 100
    },
    {
      label: "邮箱号",
      prop: "email",
      minWidth: 150
    },
    {
      label: "到期时间",
      minWidth: 100,
      prop: "expirationTime",
      formatter: ({ expirationTime }) =>
        dayjs(expirationTime).format("YYYY-MM-DD")
    },
    {
      label: "登录时间",
      minWidth: 100,
      prop: "loginDate",
      formatter: ({ loginDate }) => {
        if (dayjs(loginDate).format("YYYY-MM-DD") == "1900-01-01") {
          return "";
        } else {
          return dayjs(loginDate).format("YYYY-MM-DD");
        }
      }
    },
    {
      label: "登录IP",
      prop: "loginIP",
      minWidth: 100
    },

    {
      label: "操作",
      fixed: "right",
      width: 150,
      slot: "operation"
    }
  ];

  async function onSearch() {
    if (form.ClassId != "") {
      loading.value = true;
      const { data } = await GetPageStu({
        pageindex: pagination.currentPage,
        pagesize: pagination.pageSize,
        ...form
      });
      dataList.value = data.list;
      pagination.total = data.totalCount;
      loading.value = false;
    }
  }

  async function addStudent(StudentToRef: FormInstance | undefined) {
    (StudentToRef as any).validate(async valid => {
      if (!valid) return;
      const respone = await BatchAddStu(addStudentDto);
      if (respone.status == 200) {
        form.ClassId = addStudentDto.ClassId;
        ElMessage.success(respone.msg);
        CloseAddPanel(StudentToRef);
        ClassOnChange()
        GetAllDelegateTeamByClassId(form.ClassId);
        onSearch();

      } else {
        ElMessage.warning(respone.msg);
      }
    });
  }

  function changePasswordType() {
    if (addStudentDto.PasswordType == "1") {
      addStudentDto.Password = "888888";
    } else if (addStudentDto.PasswordType == "2") {
      let code = "";
      for (let i = 0; i < 6; i++) {
        code += parseInt(Math.random() * 10);
      }
      addStudentDto.Password = code;
    }
  }

  function ShowAddStudentPanel() {
    addPanelVisible.value = true;
  }

  function CloseAddPanel(row: FormInstance | undefined) {
    if (!row) return;
    addPanelVisible.value = false;
    row.resetFields();
  }

  const updateStudent = (StudentToRef: FormInstance | undefined) => {
    (StudentToRef as any).validate(async valid => {
      if (!valid) return;
      const respone = await SaveStudent(updateStudentDto);
      if (respone.success) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        CloseUpdatePanel(StudentToRef);
        onSearch();
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  };

  // 修改用户
  function ShowUpdateStudentPanel(row: any | undefined) {
    updateStudentDto.ClassId = row.classId;
    updateStudentDto.UserName = row.userName;
    updateStudentDto.UserId = row.userId;
    updateStudentDto.Email = row.email;
    updateStudentDto.ExpirationTime = row.expirationTime;
    updateStudentDto.Sex = row.sex;
    updateStudentDto.PassWord = row.passWord;
    updateStudentDto.TelePhone = row.telePhone;
    updateStudentDto.StudentNumber = row.studentNumber;
    updateStudentDto.DelegateTeamId = row.delegateTeamId;
    updatePanelVisible.value = true;
  }

  // 关闭
  function CloseUpdatePanel(row: FormInstance | undefined) {
    if (!row) return;
    updatePanelVisible.value = false;
    row.resetFields();
  }

  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await Delete({ userId: row.userId });
      if (res.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch();
      } else {
        ElMessage.error(res.msg)
      }
      // 确定
    }).catch(() => { })

  }

  //选择班级改变事件
  async function ClassOnChange() {
    const respone = await GetAllDelegateTeamByClassId(form.ClassId);
    console.log("respone", respone)
    if (respone.success) {
      form.DelegateTeamId = "";
      delegateTeamList.value = respone.data;
    }
    pagination.currentPage = 1;
    onSearch();
  }

  //获取班级
  async function InitClass() {
    const respone = await GetAllClass();
    if (respone.success) {
      classList.value = respone.data;
    }
  }

  onMounted(() => {
    InitClass();
  });

  function handleSizeChange(val: number) {
    onSearch();
  }

  function handleCurrentChange(val: number) {
    onSearch();
  }



  return {
    form,
    rules,
    loading,
    columns,
    dataList,
    pagination,
    addStudentDto,
    updateStudentDto,
    updatePanelVisible,
    addPanelVisible,
    delegateTeamList,
    sex,
    classList,
    onSearch,
    updateStudent,
    CloseUpdatePanel,
    ShowUpdateStudentPanel,
    addStudent,
    CloseAddPanel,
    ShowAddStudentPanel,
    changePasswordType,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    ClassOnChange
  };
}
